<template>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="View" @click="VerifyPaperTitle()">检测试卷标题</el-button>
      </el-form-item>
      <el-form-item label="发布日期" prop="publish_time">
        <el-input v-model="ruleForm.publish_time" clearable/>
        <!-- <el-date-picker
          v-model="ruleForm.publish_time"
          type="date"
          label="试卷发布日期"
          placeholder="选择日期"  
        /> -->
      </el-form-item>
     
      <el-form-item label="备注" prop="description">
        <el-input v-model="ruleForm.description" type="textarea" clearable />
      </el-form-item>   
      <el-form-item label="公开" prop="open_level">
        <el-radio-group v-model="ruleForm.open_level">
          <el-radio label="public" >公开</el-radio>
          <el-radio label="private" >私有</el-radio>
          <el-radio label="friend" disabled>好友可见</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-text>{{ ruleForm.grade }}</el-text>
        <!-- <el-radio-group v-model="ruleForm.grade">
          <el-radio label=3 >高三</el-radio>
          <el-radio label=2 >高二</el-radio>
          <el-radio label=1 >高一</el-radio>
        </el-radio-group> -->
      </el-form-item> 
      
      <el-form-item>
        <el-switch
          v-model="ruleForm.is_joint"
          class="mb-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;"
          active-text= "地市联考卷"
          inactive-text= "原创/改编卷"
          active-value = true
          inactive-value = false
          @change="handleSwithChange()"
          :disabled="isStaff()==false"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="warning" :icon="Back"  disabled>上一步</el-button>
        <el-button type="primary" @click="viewAllInformation()">预览</el-button>
        <el-button type="primary" ref="submitButton" @click="submitForm()" :disabled="state.submitButtonDisabled">提交</el-button>        
      </el-form-item>
    </el-form>
    <ShowQuestionReadOnlyDialog ref="showQuestionReadOnlyDialog" :questionList="paperquestionList"></ShowQuestionReadOnlyDialog>
  </template>
  
<script setup>
  import axios from '@/utils/axios'
  import { useStore } from 'vuex'
  import { reactive, ref, onMounted } from 'vue'
  import { View  } from '@element-plus/icons-vue'
  import { UploadFilled, Back } from '@element-plus/icons-vue'
  import { localGet, uploadPaperFileServer, convertQuestionFormat, deleteQuestionItem,deepClone} from '@/utils'
  import { ElMessage } from 'element-plus'
  import ShowQuestionReadOnlyDialog from '@/views/ShowQuestionReadOnlyDialog.vue'
  import { useRouter, } from 'vue-router'
  
  const submitButton = ref(null)
  const router = useRouter()
  const formSize = ref('default')
  const ruleFormRef = ref(null)
  const showQuestionReadOnlyDialog = ref(null)
  let paperquestionList = reactive([])
  const store=useStore()
  const ruleForm = reactive({
    title: '试卷题目',
    description: '',
    is_joint: false,
    open_level: 'private',
    score: 50,
    publish_time:'',
    grade:2,
  })
  const state = reactive({
    token: "",
    submitButtonDisabled: false
  })
    
  onMounted(()=>{    
    // console.log("尝试获取全局题目列表：",store.state.paperquestionList)
    // 对数组进行深拷贝
    paperquestionList = deepClone(store.state.paperquestionList)
    console.log("深拷贝后题目：", paperquestionList)
    if (paperquestionList){
      let reference = paperquestionList[0].reference
      ruleForm.title = reference
      ruleForm.grade = paperquestionList[0].grade
    }  
  })
  const rules = reactive({
    title: [
      { required: true, message: '请输入试卷标题', trigger: 'blur' },
      { min: 4, max: 50, message: '长度的合适范围是4-50字', trigger: 'blur' },
    ],
    description: [
      {
        required: false,
        message: '请输入备注',
        trigger: 'change',
      },
    ],
    open_level: [
      {
        required: true,
        message: '请选择公开方式',
        trigger: 'change',
      },
    ],
    publish_time: [
    {
      type: 'date',
      required: true,
      message: '选择日期',
      trigger: 'change',
    },
    ],
    grade:[
      {
        required: true,
        message: '请选择年级段',
        trigger: 'change',
      }
    ],
  })
  // 开关切换事件
  const handleSwithChange=()=>{
    console.log("开关切换了", ruleForm.is_joint)
  }
  // 判断当前用户是否为管理员
  const isStaff=()=>{
    let localUser = localGet('user_information')
    return localUser.is_staff == true
  }
  // 提交试卷和题目列表，持久化到数据库
  const submitForm =  () => {
    state.submitButtonDisabled=true
    ruleFormRef.value.validate((vaild, obj) => {
      if (vaild) {
        if(isStaff()){
          ruleForm.is_joint = true
        }else{
          ruleForm.is_joint = false
        }
        // 调整试题列表，去掉无关项
        // console.log("转换之前的题目列表：",paperquestionList)
        let deleteList=["answer_front", "content_front","explain_front","images","images_explain","knowledgepoint_cn","type_cn","grade"]
        for(let item of paperquestionList){
          item=convertQuestionFormat(item)
          item=deleteQuestionItem(item, deleteList)
        }    
        // console.log("题目列表要发给后端了：",paperquestionList)
        console.log("要发给后端啦试卷:",ruleForm)
        let params = { paperInformation: ruleForm, questionList: paperquestionList, type: "importQuestionsAndPaper"}    
          axios.post('/GeneratePaper2Database/', params).then((result) => {
            if(result.code==200){
              console.log(result)
              ElMessage.success( '试卷提交成功,请到试卷管理栏目，申请试卷上线')            
              var r=confirm("上传成功。是否返回首页？");
              if (r==true){
                  router.push("/")
              }else{
                router.push("/addPaperByFileStepOne?importQuestionType=importQuestionsAndPaper")
              }
            }else
            if(result.code==201){
              console.log(result)
              ElMessage.success( '试卷提交成功,申请试卷上线失败，试卷管理手工申请上线！')            
              var r=confirm("上传成功。是否返回首页？");
              if (r==true){
                  router.push("/")
              }else{
                router.push("/addPaperByFileStepOne?importQuestionType=importQuestionsAndPaper")
              }
            }else{
              console.log("提交错误:", result)
            }
          })
        
      }else{                //输出表单没有通过的原因
        console.log("表单没有通过！",obj)
        for (let key in obj) {
          console.log(obj[key][0].message)
          return false;
        }
      }
    })
  }

  //检测试卷名称是否重名
  const VerifyPaperTitle=()=>{
    axios.get('/VerifyPaperName/',{params:{paper_title:ruleForm.title}}).then(res => {
    if (res.code==200){
      ElMessage.success('恭喜，该标题可以使用^_^')
      return true
    }else{
      ElMessage.error('sorry，该标题已被使用*_*,请更换新标题')
      return false
    }        
  })
  .catch((error)=>{
    console.log("error")
  })   
  }
  const viewAllInformation=()=>{
    injectFormIntoQuestionList()
    console.log("申请打开题目弹窗并传输试卷资料：",paperquestionList)    
    showQuestionReadOnlyDialog.value.open(paperquestionList)
  }
  //把表单里的内容注入到questionList中
  const injectFormIntoQuestionList=()=>{
    paperquestionList =[].concat(JSON.parse(JSON.stringify(store.state.paperquestionList))) 
    for(let i=0;i<paperquestionList.length;i++){
      paperquestionList[i].reference = ruleForm.title
      paperquestionList[i].publish_time = ruleForm.publish_time
      paperquestionList[i].open_level = ruleForm.open_level
    }
  }
</script>
  